package com.xlh.dokka.svc.core.scheduler;


import com.xlh.dokka.svc.core.model.ContainerConfig;
import com.xlh.dokka.svc.core.model.GpuNode;
import com.xlh.dokka.svc.core.model.Node;
import com.xlh.dokka.svc.core.scheduler.filter.Filter;
import com.xlh.dokka.svc.core.scheduler.strategy.Strategy;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author cheer
 */
public class Scheduler {

    private List<Filter> filters;

    private Strategy strategy;

    public Scheduler(List<Filter> filters, Strategy strategy) {
        this.filters = filters;
        this.strategy = strategy;
    }

    public Node selectNodeForContainers(ContainerConfig containerConfig, List<Node> nodes) {
        List<Node> accepted = Filter.applyFilters(filters, containerConfig, nodes);

        if (containerConfig.getHost() != null) {
            for (Node node : accepted) {
                if (StringUtils.equals(containerConfig.getHost(), node.getIp())) {
                    return node;
                }
            }
            return null;
        }

        List<Node> sorted = strategy.rankAndSort(containerConfig, accepted);
        if (CollectionUtils.isNotEmpty(sorted)) {
            return sorted.get(0);
        }
        return null;
    }

    public GpuNode selectGpuNodeForContainers(ContainerConfig containerConfig, List<GpuNode> gpuNodes) {
        List<GpuNode> accepted = Filter.applyGpuFilters(filters, containerConfig, gpuNodes);
        List<GpuNode> sorted = strategy.rankAndSortGpu(containerConfig, accepted);
        if (CollectionUtils.isNotEmpty(sorted)) {
            return sorted.get(0);
        }
        return null;
    }
}
